package com.yvon.maple.service.auth.valicode.validate.code.generator;

import cn.hutool.core.lang.RegexPool;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import com.yvon.boot.common.result.GlobalException;
import com.yvon.maple.service.auth.param.CodeParam;
import com.yvon.maple.service.auth.service.SecurityUserService;
import com.yvon.maple.service.auth.valicode.validate.code.properties.CodeProperties;
import com.yvon.maple.service.auth.valicode.validate.code.repository.CodeRepository;
import com.yvon.maple.service.auth.valicode.vo.CodeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Objects;

/**
 * @author : Yvon
 * @since : 2022-01-27
 */
@Slf4j
@Component(EmailCodeGenerator.GENERATOR)
public class EmailCodeGenerator implements CodeGenerator{

    public static final String GENERATOR = "emailCodeGenerator";


    /**
     * 系统配置
     */
    @Autowired
    private CodeProperties codeProperties;

    @Autowired
    private CodeRepository codeRepository;

    @Autowired
    private SecurityUserService securityUserService;


    @Override
    public CodeVo generate(CodeParam param) {
        Assert.isTrue(ReUtil.contains(RegexPool.EMAIL, param.getKey()), "电子邮箱格式有误");
        CodeVo codeVo = codeRepository.get(param.getValidateType(), param.getKey());
        if (Objects.nonNull(codeVo) && !codeVo.isExpire()) {
            throw new GlobalException("请勿频繁发送邮件");
        }
        securityUserService.loadUserByEmail(param.getKey());
        String code = RandomUtil.randomNumbers(codeProperties.getEmail().getLength());
        return new CodeVo(code, codeProperties.getEmail().getExpire(), param.getKey());
    }
}
